package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * 配送货添加
 *
 * @author wu
 */
public class DeliveryAddFragment extends DeliveryBaseFragment {

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    if (NavUtils.getParentActivityName(getActivity()) != null) {
      ((BaseVolleyActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setTitle(R.string.addDelivery);

    mId = UUID.randomUUID().toString();
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_save_submit, menu);
    menu.getItem(1).setTitle(R.string.saveAndSubmit);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      /**
       * 响应返回按钮
       */
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;
      // 保存
      case R.id.menu_item_save:
        if (TextUtils.isEmpty(mDeliveryPerson_addEditDelivery.getText().toString())) {
          MyUtils.show(getActivity(), R.string.chooseDeliveryPer);
        } else if (TextUtils.isEmpty(mMainGoods_addEditDelivery.getText().toString())) {
          MyUtils.show(getActivity(), R.string.chooseMainGoods);
        } else if (TextUtils.isEmpty(mDeliveryAddress_addEditDelivery.getText().toString())) {
          MyUtils.show(getActivity(), R.string.chooseDeliveryAdd);
        } else {
          AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
          dialog.setTitle(R.string.restart_title);
          dialog.setMessage(R.string.ifSave);
          dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              volleyPostSave();
            }
          });

          dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              dialog.dismiss();
            }
          });
          dialog.create().show();
        }
        break;
      case R.id.menu_item_submit:
        if (TextUtils.isEmpty(mDeliveryPerson_addEditDelivery.getText().toString())) {
          MyUtils.show(getActivity(), R.string.chooseDeliveryPer);
        } else if (TextUtils.isEmpty(mMainGoods_addEditDelivery.getText().toString())) {
          MyUtils.show(getActivity(), R.string.chooseMainGoods);
        } else if (TextUtils.isEmpty(mDeliveryAddress_addEditDelivery.getText().toString())) {
          MyUtils.show(getActivity(), R.string.chooseDeliveryAdd);
        } else {
          AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
          dialog.setTitle(R.string.restart_title);
          dialog.setMessage(R.string.cannotEdit);
          dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              volleyPostStart();
            }
          });

          dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              dialog.dismiss();
            }
          });
          dialog.create().show();
        }
        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  private void volleyPostSave() {
    MyUtils.showDialogLoading(getActivity(), R.string.loadingSave);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DELIVERT_SAVE);
    HashMap<String, String> params = getparams();
    params.put("id", mId);// id 新建时本地生成
    params.put("dataStatus", "new");// 数据状态（新增时固定值”new”）
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
        String resutl = success.getResult();
        if (SuccessMessage.SUCCESS.equalsIgnoreCase(resutl)) {
          MyUtils.show(getActivity(), R.string.save_success);
          MyUtils.dismissDialog();
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }

        if (SuccessMessage.FAILURE.equalsIgnoreCase(resutl)) {
          MyUtils.show(getActivity(), R.string.save_failure);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.save_failure);
      }
    });

    LogUtil.i("saveparams=====" + params);
  }

  /**
   * 保存时的参数保存到hashmap
   *
   * @return params
   */
  public HashMap<String, String> getparams() {
    String mainGoods = mMainGoods_addEditDelivery.getText().toString().trim();
    String logisticsNum = mLogisticsNum_addEditDelivery.getText().toString().trim();
    String log = mDeliveryText_addEditDelivery.getText().toString().trim();
    String fee = mDeliveryFee_addEditDelivery.getText().toString().trim();
    mStaffName = mDeliveryPerson_addEditDelivery.getText().toString().trim();
    mAddressName = mDeliveryAddress_addEditDelivery.getText().toString().trim();
    HashMap<String, String> params = new HashMap<String, String>();

    params.put("distributionStaffId", mjobNos); // 配送负责人工号
    params.put("distributionStaffName", mStaffName);// 配送负责人名称

    params.put("mainGoods", mainGoods);// 配送货物
    if (!TextUtils.isEmpty(mCustomerId)) {
      params.put("customerId", mCustomerId); // 客户ID
    }
    if (!TextUtils.isEmpty(mCustomerName)) {
      params.put("customerName", mCustomerName); // 客户名称
    }
    if (!TextUtils.isEmpty(mIfThirdLogistics)) {
      params.put("ifThirdlogistics", mIfThirdLogistics);// 是否第三方物流
    } else {
      params.put("ifThirdlogistics", VALUE_FALSE);
    }

    if (!TextUtils.isEmpty(mLogisticsName)) {
      params.put("logisticsCompany", mLogisticsName);// 物流公司名称
    }
    if (!TextUtils.isEmpty(logisticsNum)) {
      params.put("logisticsNumber", logisticsNum);// 物流单号
    }

    if (!TextUtils.isEmpty(log)) {
      params.put("distributionLog", log);// 配送日志
    }

    if (!TextUtils.isEmpty(mContractId)) {
      params.put("contractId", mContractId);// 关联销售合同ID
    }
    if (!TextUtils.isEmpty(mContractCode)) {
      params.put("contractName", mContractCode);// 关联合同编号
    }

    params.put("distributionAddress", mAddressName);// 配送地址
    if (!TextUtils.isEmpty(mOrderId)) {
      params.put("moutbillId", mOrderId); // 关联出库单ID
    }
    if (!TextUtils.isEmpty(mOrderNumber)) {
      params.put("moutbillName", mOrderNumber); // 关联出库单编号
    }
    if (!TextUtils.isEmpty(fee)) {
      params.put("distributionCost", fee);// 配送费
    }

    if (!TextUtils.isEmpty(mIfPay)) {
      params.put("ifPay", mIfPay);// 是否支付
    } else {
      params.put("ifPay", VALUE_FALSE);
    }
    return params;
  }

  /**
   * 启动流程
   */
  protected void volleyPostStart() {
    MyUtils.showDialogLoading(getActivity(), R.string.loadingStart);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DELIVERY_RUN);
    HashMap<String, String> params = getparams();
    params.put("id", mId);// id 新建时本地生成
    params.put("dataStatus", "waitCheck");
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        try {
          SuccessMessage message = new Gson().fromJson(arg0, SuccessMessage.class);
          String result = message.getResult();
          String messages = message.getMessage();
          if (SuccessMessage.SUCCESS.equalsIgnoreCase(result)) {
            ToastUtil.show(R.string.startFolwSuccess);
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          } else {
            ToastUtil.show(messages);
          }
        } catch (Exception e) {
          MyUtils.show(getActivity(), R.string.startFolwFail);
          LogUtil.e("startError", e);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.startFolwFail);
      }
    });
  }
}
